import {ref, reactive} from 'vue'
import { defineStore } from 'pinia'

import type {AxiosResponse} from "axios";

import type {JsonResult} from "@/api";

import UserAPI from "@/api/user";
import RoleAPI from "@/api/role";

import {StatusCode} from "@/api";
import type {User} from "@/api/user";
import type {Role} from "@/api/role";

interface UserStore {
  isLogged: boolean,
  token: string | null,
  info: User | null,
  role: Role | null,
  login(username: string, password: string): Promise<AxiosResponse<JsonResult>>,
  myInfo(): Promise<AxiosResponse<JsonResult>>,
  logout(): void,
  hasPermission(permission: string): boolean
}

export const useStore = defineStore('main', () => {
  const user = reactive<UserStore>({
    isLogged: false, token: null, info: null, role: null,

    login: async (username, password) => {
      const response = await UserAPI.login(username, password);

      if(response.data.code === StatusCode.LOGIN_SUCCESS) {
        user.token = response.data.data.token;
        user.info = response.data.data.info;

        const resp = await RoleAPI.get(response.data.data.info.roleId);
        if(resp.data.code === StatusCode.SUCCESS) {
          user.role = resp.data.data;
        }
      }

      return response;
    },
    myInfo: async () => {
      const response = await UserAPI.myInfo();

      if(response.data.code === StatusCode.SUCCESS) {
        user.info = response.data.data;
        user.isLogged = true;

        const resp = await RoleAPI.get(response.data.data.roleId);
        if(resp.data.code === StatusCode.SUCCESS) {
          user.role = resp.data.data;
        }
      } else if(response.data.code === StatusCode.NOT_LOGIN) {
        user.logout();
      }

      return response;
    },
    logout: () => { user.token = user.info = user.role = null; user.isLogged = false; },
    hasPermission: (permission) => {
      return false;
    }
  });

  return { user }
}, { persist: { paths: ['user.token'] } });
